/**
 * 
 */
package lt.ruta.ui;

import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;

import lt.ruta.data.Messages;
import lt.ruta.data.Record;
import lt.ruta.data.Table;
import lt.ruta.data.TableIterator;

/**
 * @author Vincentas
 *
 */
public class InfoForm extends Form {

	private Table table;
	
	private StringItem expenseStringItem = null;
	
	private StringItem incomeStringItem = null;
	
	private StringItem balanceStringItem = null;
	
	private StringItem recordsStringItem = null;
	
	public InfoForm(String title, Table table) {
		super(title);
		
		this.table = table;
		
		append(getExpenseStringItem());
		append(getIncomeStringItem());
		append(getBalanceStringItem());
		append(getRecordsStringItem());
		
		update();
	}
	
	/**
	 * @return the recordsStringItem
	 */
	public StringItem getRecordsStringItem() {
		if (recordsStringItem == null) {
			recordsStringItem = new StringItem(Messages.get("infoForm.recordsStringItem.label"), "0");
			
		}

		return recordsStringItem;
	}

	/**
	 * @return the expenseStringItem
	 */
	public StringItem getExpenseStringItem() {
		if (expenseStringItem == null) {
			expenseStringItem = new StringItem(Messages.get("infoForm.expenseStringItem.label"), "-100.14 Lt");
		}

		return expenseStringItem;
	}
	
	/**
	 * @return the balanceStringItem
	 */
	public StringItem getBalanceStringItem() {
		if (balanceStringItem == null) {
			balanceStringItem = new StringItem(Messages.get("infoForm.balanceStringItem.label"), "123.01 Lt");
			
		}

		return balanceStringItem;
	}

	/**
	 * @return the incomeStringItem
	 */
	public StringItem getIncomeStringItem() {
		if (incomeStringItem == null) {
			incomeStringItem = new StringItem(Messages.get("infoForm.incomeStringItem.label"), "71431.32 Lt");
		}

		return incomeStringItem;
	}
	
	public void update() {		
		double income = 0;
		double expense = 0;
		
		TableIterator iterator = getTable().getIterator();
		try {
			while (iterator.hasNext()) {
				Record record = iterator.getNext();
				
				double amount = record.getAmountDouble();
				if (amount > 0) {
					income += amount;				
				} else {
					expense += amount;
				}
			}
		} finally {
			iterator.destroy();
		}
		
		double balance = income + expense;
		
		getIncomeStringItem().setText(toCurrency(income));
		getExpenseStringItem().setText(toCurrency(expense));
		getBalanceStringItem().setText(toCurrency(balance));
		getRecordsStringItem().setText(String.valueOf(getTable().getSize()));
	}
	
	private String toCurrency(double value) {
		String currencySymbol = Messages.get("app.currencySymbol");
		return Double.toString(value) + " " + currencySymbol;
	}

	/**
	 * @return the table
	 */
	public Table getTable() {
		return table;
	}	
}
